#include "dataconversion.h"
#include <QDateTime>
#include <QtXlsx/xlsxdocument.h>
#include <QtXlsx/xlsxworksheet.h>
#include <QtXlsx/xlsxworkbook.h>
#include <QTextStream>
#include <QFile>




DataConversion::DataConversion(QObject *parent)
    : QObject{parent}
{
    formatVector.clear();
    mDataVector = new std::vector<QByteArray*>;
    mDataVector->clear();
}

void DataConversion::readFormatFile(QString filePath)
{
    // 打开 Excel 文件
    QXlsx::Document xlsx(filePath);

    // 选择要读取的工作表
    QXlsx::AbstractSheet* abstractSheet = xlsx.sheet("Conversion");

    // 将 AbstractSheet* 转换为 Worksheet*
    QXlsx::Worksheet *sheet = dynamic_cast<QXlsx::Worksheet*>(abstractSheet);

    // 获取工作表的有效范围
    QXlsx::CellRange dimension = sheet->dimension();
    int rowCount = dimension.rowCount();

    // 逐行读取第6列非空的内容，将其放入动态数组中
    for(int row = 2; row <= rowCount; ++row){
        QString type = sheet->read(row, 2).toString();              // 读取数据类型
        QString value = sheet->read(row, 4).toString();             // 读取字节长度
        if (value.isEmpty()) continue; // 跳过空值
        formatVector.push_back(value.toUInt());
        dataTypeVector.push_back(type);
    }

}

void DataConversion::conversion(QString dataFilePath)
{
    // 打开CSV文件
    QFile file(dataFilePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "Failed to open the datafile: ";
    }

    // 创建一个读取文本流
    QTextStream in(&file);



    // 读取文件内容并显示在控制台
    while (!in.atEnd()) {
        // 存储一行转后的Bytes数据
        QByteArray* pData = new QByteArray;
        QDataStream stream(pData, QIODevice::WriteOnly);
        stream.setByteOrder(QDataStream::LittleEndian);


        QString line = in.readLine();
        if(line.contains("TrainId") || line.contains("SystemAB") || line.contains("Time")) {
            continue;    // 跳过首行标题行
        }

        // 读取数据
        QStringList fields = line.split(',');

        // 根据格式进行数据转化
        int index = 0;
        int vectorIndex = 0;

        for(const QString &str : std::as_const(fields)){
            // 转化A/B系
            if (index == 1) {                
                if(dataTypeVector[vectorIndex] == "UINT") {
                    quint8 value = 0;
                    if(str=="A"){
                        value = 1;
                    }
                    if(str=="B"){
                        value = 2;
                    }
                    stream << value;
                } else {
                    qint8 value = 0;
                    if(str=="A"){
                        value = 1;
                    }
                    if(str=="B"){
                        value = 2;
                    }
                    stream << value;
                }

                ++vectorIndex;
                index++;
                continue;
            }

            // 转化主备系
            if (index == 2) {
                if(dataTypeVector[vectorIndex] == "UINT") {
                    quint8 value = 0;
                    if(str == "M"){
                        value = 1;
                    }
                    if(str == "S"){
                        value = 2;
                    }
                    stream << value;
                } else {
                    qint8 value = 0;
                    if(str == "M"){
                        value = 1;
                    }
                    if(str == "S"){
                        value = 2;
                    }
                    stream << value;
                }

                index++;
                ++vectorIndex;
                continue;
            }


            // 单独转化年月日时分秒
            if (index == 5) {
                QDateTime dateTime = QDateTime::fromString(str, "yyyy-MM-dd hh:mm:ss");

                if (!dateTime.isValid()) {
                    qDebug()<<"the format of DateTime is invalid!";
                }

                // 转化年
                quint16 tYear = dateTime.date().year();
                stream << tYear;
                ++vectorIndex;

                // 转化月
                quint8 tMonth = dateTime.date().month();
                stream << tMonth;
                ++vectorIndex;

                // 转化日
                quint8 tDay = dateTime.date().day();
                stream << tDay;
                ++vectorIndex;

                // 转化时
                quint8 tHour = dateTime.time().hour();
                stream << tHour;
                ++vectorIndex;

                // 转化分
                quint8 tMinute = dateTime.time().minute();
                stream << tMinute;
                ++vectorIndex;

                // 转化秒

                quint8 tSecond;
                tSecond = dateTime.time().second();
                stream << tSecond;
                ++vectorIndex;

                ++index;
                continue;
            }

            // 常规值的转化
            switch(formatVector[vectorIndex] / 8) {
            case 1:
            {
                if(dataTypeVector[vectorIndex] == "UINT") {
                    quint8 value = str.toUInt();
                    stream << value;
                } else {
                    qint8 value = str.toInt();
                    stream << value;
                }
                break;
            }
            case 2:
            {
                if(dataTypeVector[vectorIndex] == "UINT") {
                    quint16 value = str.toUInt();
                    stream << value;
                } else {
                    qint16 value = str.toInt();
                    stream << value;
                }
                break;
            }
            case 4:
            {
                if(dataTypeVector[vectorIndex] == "UINT") {
                    quint32 value = str.toUInt();
                    stream << value;
                } else {
                    qint32 value = str.toInt();
                    stream << value;
                }
                break;
            }
            default:
                break;
            }
            ++index;
            ++vectorIndex;
        }

        mDataVector->push_back(pData);
    }


    // 关闭文件
    file.close();

}

void DataConversion::save(QString logFilePath)
{
    // 打开日志文件
    QFile logfile(logFilePath);
    if (!logfile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "Failed to open the logfile: ";
    }

    // 创建一个输出文本流
    QDataStream out(&logfile);


    // 遍历每一行的Byte数据后写入文件
    for(const auto &byte : std::as_const(*mDataVector)){
        out << byte->toHex().toBase64();
    }

    qDeleteAll(mDataVector->begin(), mDataVector->end());

    delete mDataVector;
    mDataVector = nullptr;

    logfile.close();

}


